<template>
  <div>
    <!-- 全局样式修复 -->
    <style>
      .recording-replay-modal .rr-player {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
        border: 1px solid #dcdfe6 !important;
        border-radius: 6px !important;
        overflow: hidden !important;
      }
      .recording-replay-modal .rr-player * {
        box-sizing: border-box !important;
      }
      .recording-replay-modal .rr-player .rr-controller {
        font-size: 14px !important;
        color: #333 !important;
        background: #fff !important;
        border-top: 1px solid #dcdfe6 !important;
      }
      .recording-replay-modal .rr-player .rr-controller button {
        font-size: 12px !important;
        color: #333 !important;
        cursor: pointer !important;
        background: #fff !important;
        border: 1px solid #dcdfe6 !important;
        border-radius: 4px !important;
        margin: 0 4px !important;
        padding: 4px 8px !important;
      }
      .recording-replay-modal .rr-player .rr-controller button:hover {
        background: #f5f7fa !important;
        border-color: #409eff !important;
      }
      .recording-replay-modal .rr-player .rr-controller button:disabled {
        opacity: 0.6 !important;
        cursor: not-allowed !important;
        background: #f5f7fa !important;
      }
      .recording-replay-modal .rr-player .rr-controller select {
        border: 1px solid #dcdfe6 !important;
        border-radius: 4px !important;
        padding: 2px 4px !important;
        background: #fff !important;
      }
      .recording-replay-modal .rr-player .rr-timeline {
        background: #f5f7fa !important;
      }
      .recording-replay-modal .rr-player .rr-progress {
        background: #409eff !important;
      }
    </style>

    <!-- 浮动面板 -->
    <div v-if="isMinimized" 
         class="recording-panel-minimized"
         :style="{
           position: 'fixed',
           bottom: '20px',
           right: '20px',
           zIndex: 9999,
           background: '#fff',
           borderRadius: '50%',
           width: '60px',
           height: '60px',
           display: 'flex',
           alignItems: 'center',
           justifyContent: 'center',
           boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
           cursor: 'pointer',
           border: isRecording ? '3px solid #f56c6c' : '1px solid #dcdfe6'
         }"
         @click="isMinimized = false">
      <el-icon :size="24" :color="isRecording ? '#f56c6c' : '#409eff'">
        <VideoCamera />
      </el-icon>
    </div>

    <el-card v-else
             :class="`recording-panel ${className || ''}`"
             :style="{
               position: 'fixed',
               bottom: '20px',
               right: '20px',
               width: '320px',
               zIndex: 9999,
               boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
             }"
             shadow="hover">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>🎬 录制面板</span>
          <el-tooltip content="最小化" placement="top">
            <el-button type="text" 
                       size="small" 
                       @click="isMinimized = true">
              −
            </el-button>
          </el-tooltip>
        </div>
      </template>

      <el-space direction="vertical" style="width: 100%;" :size="12">
        <!-- 录制状态 -->
        <div style="text-align: center;">
          <span v-if="isRecording" style="color: #f56c6c;">
            🔴 录制中... {{ formatTime(recordDuration) }}
          </span>
          <span v-else>
            准备就绪 - 共 {{ events.length }} 个事件
          </span>
        </div>

        <!-- 控制按钮 -->
        <el-space wrap style="width: 100%; justify-content: center;" :size="8">
          <el-tooltip content="开始录制" placement="top">
            <el-button type="primary" 
                       size="small"
                       :disabled="isRecording"
                       @click="startRecording">
              📹 录制
            </el-button>
          </el-tooltip>

          <el-tooltip content="停止录制" placement="top">
            <el-button type="danger" 
                       size="small"
                       :disabled="!isRecording"
                       @click="stopRecording">
              ⏹️ 停止
            </el-button>
          </el-tooltip>

          <el-tooltip content="回放" placement="top">
            <el-button size="small"
                       :disabled="events.length === 0 || isRecording"
                       @click="startReplay">
              ▶️ 回放
            </el-button>
          </el-tooltip>

          <el-tooltip content="下载数据" placement="top">
            <el-button size="small"
                       :disabled="events.length === 0"
                       @click="downloadData">
              💾 下载
            </el-button>
          </el-tooltip>
        </el-space>
      </el-space>
    </el-card>

    <!-- 回放弹框 -->
    <el-dialog v-model="isModalVisible"
               title="录制回放"
               width="900px"
               center
               destroy-on-close
               class="recording-replay-modal"
               @close="closeModal">
      <div style="margin-bottom: 16px;">
        <el-progress :percentage="Math.round(playProgress)"
                     :status="isPlaying ? undefined : 'exception'"
                     :show-text="true" />
        <div style="text-align: center; margin-top: 8px;">
          <span style="color: #666;">
            {{ isPlaying ? '正在回放...' : '回放已暂停' }} | 总时长: {{ formatTime(recordDuration) }}
          </span>
        </div>
      </div>

      <div ref="replayTargetRef"
           :style="{
             width: '100%',
             height: '600px',
             border: '1px solid #dcdfe6',
             borderRadius: '6px',
             background: '#f5f7fa'
           }" />

      <template #footer>
        <el-button @click="closeModal">关闭</el-button>
        <el-button :disabled="!isPlaying" @click="pauseReplay">
          ⏸️ 暂停
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoCamera } from '@element-plus/icons-vue'
import * as rrweb from 'rrweb'
import rrwebPlayer from 'rrweb-player'
import type { RRwebPlayerOptions } from 'rrweb-player'

// Props
interface Props {
  className?: string
}

withDefaults(defineProps<Props>(), {
  className: ''
})

// rrweb相关类型定义
type EventWithTime = {
  timestamp: number
  delay?: number
}

interface CustomEvent extends Event {
  detail?: unknown
  target: EventTarget | null
}

// 响应式状态
const isRecording = ref(false)
const isPlaying = ref(false)
const events = ref<EventWithTime[]>([])
const recordDuration = ref(0)
const playProgress = ref(0)
const isModalVisible = ref(false)
const isMinimized = ref(false)

// 引用
const stopFnRef = ref<(() => void) | null>(null)
const replayerRef = ref<rrwebPlayer | null>(null)
const startTimeRef = ref<number | null>(null)
const recordTimerRef = ref<NodeJS.Timeout | null>(null)
const replayTargetRef = ref<HTMLDivElement | null>(null)

// 格式化时间显示
const formatTime = (ms: number): string => {
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds
    .toString()
    .padStart(2, '0')}`
}

// 开始录制
const startRecording = async () => {
  if (isRecording.value) return

  try {
    // 检查rrweb是否可用
    if (typeof rrweb === 'undefined') {
      ElMessage.error('rrweb库未加载，请检查页面配置')
      return
    }

    // 清空之前的数据
    events.value = []
    recordDuration.value = 0
    playProgress.value = 0
    startTimeRef.value = Date.now()

    // 开始rrweb录制
    stopFnRef.value = rrweb.record({
      emit: (event: EventWithTime) => {
        events.value.push(event)
      },
      checkoutEveryNth: 100, // 每 100 个 event 重新制作快照
      recordCanvas: true, // 录制canvas
      inlineStylesheet: true, // 内联样式表
      inlineImages: true, // 内联图片为base64，避免blob URL问题
      // 定制的选项
      plugins: [
        rrweb.getRecordConsolePlugin({
          level: ['info', 'log', 'warn', 'error'],
          lengthThreshold: 10000,
          stringifyOptions: {
            stringLengthLimit: 1000,
            numOfKeysLimit: 100,
            depthOfLimit: 1
          },
          logger: window.console
        })
      ]
    }) as unknown as null

    isRecording.value = true
    ElMessage.success('开始录制')
    console.log('开始录制用户操作')

    // 启动计时器
    recordTimerRef.value = setInterval(() => {
      if (startTimeRef.value) {
        const duration = Date.now() - startTimeRef.value
        recordDuration.value = duration
      }
    }, 1000)

    // 添加自定义事件监听
    addCustomEventListeners()
  } catch (error) {
    console.error('录制启动失败:', error)
    ElMessage.error('录制启动失败: ' + (error as Error).message)
  }
}

// 停止录制
const stopRecording = () => {
  if (!isRecording.value) return

  try {
    // 停止rrweb录制
    if (stopFnRef.value) {
      stopFnRef.value()
      stopFnRef.value = null
    }

    // 停止计时器
    if (recordTimerRef.value) {
      clearInterval(recordTimerRef.value)
      recordTimerRef.value = null
    }

    // 重置录制状态
    isRecording.value = false
    startTimeRef.value = null

    ElMessage.success(`录制已停止，共记录 ${events.value.length} 个事件`)
    console.log('录制已停止，共记录', events.value.length, '个事件')
  } catch (error) {
    console.error('停止录制失败:', error)
    ElMessage.error('停止录制失败')
    // 即使出错也要重置状态
    isRecording.value = false
    startTimeRef.value = null
  }
}

// 开始回放
const startReplay = async () => {
  if (events.value.length === 0) {
    ElMessage.warning('没有录制数据，请先进行录制')
    return
  }

  if (isPlaying.value) return

  // 如果正在录制，先停止录制
  if (isRecording.value) {
    stopRecording()
    // 等待录制完全停止
    await new Promise((resolve) => setTimeout(resolve, 100))
  }

  try {
    isPlaying.value = true
    isModalVisible.value = true
    playProgress.value = 0

    // 等待Modal渲染完成
    await nextTick()
    setTimeout(async () => {
      if (!replayTargetRef.value) {
        ElMessage.error('回放容器未找到')
        isPlaying.value = false
        return
      }
      // 清空回放容器
      replayTargetRef.value.innerHTML = ''

      // 创建rrwebPlayer实例
      replayerRef.value = new rrwebPlayer({
        target: replayTargetRef.value,
        props: {
          events: events.value as RRwebPlayerOptions['props']['events'],
          plugins: [
            rrweb.getReplayConsolePlugin({
              level: ['info', 'log', 'warn', 'error']
            })
          ]
        }
      })

      ElMessage.success('开始回放')
      console.log('rrwebPlayer已创建，事件数量:', events.value.length)

      // 模拟进度更新
      const totalDuration = recordDuration.value
      const progressInterval = setInterval(() => {
        playProgress.value += 100 / (totalDuration / 1000)
        if (playProgress.value >= 100) {
          clearInterval(progressInterval)
          isPlaying.value = false
          ElMessage.success('回放完成')
          playProgress.value = 100
        }
      }, 1000)
    }, 300)
  } catch (error) {
    console.error('回放启动失败:', error)
    ElMessage.error('回放启动失败: ' + (error as Error).message)
    isPlaying.value = false
  }
}

// 暂停回放
const pauseReplay = () => {
  isPlaying.value = false
  ElMessage.info('回放已暂停')
}

// 下载录制数据
const downloadData = () => {
  if (events.value.length === 0) {
    ElMessage.warning('没有录制数据可下载')
    return
  }

  try {
    const dataStr = JSON.stringify(
      {
        events: events.value,
        recordDuration: recordDuration.value,
        timestamp: Date.now(),
        userAgent: navigator.userAgent,
        url: window.location.href
      },
      null,
      2
    )

    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `recording-${new Date()
      .toISOString()
      .slice(0, 19)
      .replace(/:/g, '-')}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('录制数据已下载')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 添加自定义事件监听器
const addCustomEventListeners = () => {
  const eventTypes = [
    'modalOpened',
    'modalClosed',
    'popupOpened',
    'popupClosed'
  ]

  eventTypes.forEach((eventType) => {
    document.addEventListener(eventType, (e: Event) => {
      const customEvent = e as CustomEvent
      console.log(`自定义事件: ${eventType}`, customEvent.detail)
      if (customEvent.target && customEvent.target instanceof Element) {
        triggerManualMutation(customEvent.target)
      }
    })
  })
}

// 触发手动DOM变化
const triggerManualMutation = (element: Element) => {
  if (element) {
    const tempAttr = 'data-rrweb-' + Date.now()
    element.setAttribute(tempAttr, 'trigger')
    setTimeout(() => {
      element.removeAttribute(tempAttr)
    }, 10)
  }
}

// 关闭模态框
const closeModal = () => {
  // 清理回放器实例
  if (replayerRef.value) {
    try {
      // rrwebPlayer继承自SvelteComponent，使用$destroy方法
      ;(replayerRef.value as any).$destroy()
    } catch (e) {
      console.warn('回放器销毁失败:', e)
    }
    replayerRef.value = null
  }
  isModalVisible.value = false
  isPlaying.value = false
  playProgress.value = 0
}

// 清理资源
onUnmounted(() => {
  // 清理录制相关资源
  if (recordTimerRef.value) {
    clearInterval(recordTimerRef.value)
    recordTimerRef.value = null
  }
  if (stopFnRef.value) {
    stopFnRef.value()
    stopFnRef.value = null
  }
  // 清理回放器实例
  if (replayerRef.value) {
    try {
      // rrwebPlayer继承自SvelteComponent，使用$destroy方法
      ;(replayerRef.value as any).$destroy()
    } catch (e) {
      console.warn('回放器销毁失败:', e)
    }
    replayerRef.value = null
  }
  // 重置所有状态
  isRecording.value = false
  isPlaying.value = false
  startTimeRef.value = null
})

// 扩展Window接口以支持rrweb
declare global {
  interface Window {
    rrweb: typeof rrweb
    rrwebPlayer: typeof rrwebPlayer
  }
}
</script>

<style scoped>
.recording-panel-minimized {
  transition: all 0.3s ease;
}

.recording-panel-minimized:hover {
  transform: scale(1.1);
}

.recording-panel {
  transition: all 0.3s ease;
}
</style>